package rank

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/pkg/errors"
	"github.com/satori/go.uuid"
	"math/rand"
	"time"
)

// 排行榜场景
func RankingDemo(rdb *redis.Client) error {
	ctx := context.Background()
	// key
	zsetKey := "商品热销排行榜"
	//随机生成产品数据
	productIds := make([]string, 0, 30)
	product := make([]*redis.Z, 0, 30)
	for i := 0; i < 30; i++ {
		ids := uuid.NewV4().String()
		productIds = append(productIds, "product-"+ids)
	}
	//随机生成销量
	for _, v := range productIds {
		score := rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(100000)
		product = append(product, &redis.Z{Score: float64(score), Member: v})
	}
	//插入redis中
	err := rdb.ZAdd(ctx, zsetKey, product...).Err()
	if err != nil {
		return errors.Wrap(err,"ERR: fail to zadd")
	}
	fmt.Println("zadd success")
	//获取所有产品并按照销量排序输出
	ret := rdb.ZRevRangeWithScores(ctx, zsetKey, 0, -1).Val()
	for _, z := range ret {
		fmt.Printf("产品id：%s,产品销量：%v\n", z.Member, z.Score)
	}
	//获取销量前五并按照销量排序输出
	fmt.Println("销量前五的为下面的")
	ret = rdb.ZRevRangeWithScores(ctx, zsetKey, 0, 4).Val()
	for _, z := range ret {
		fmt.Printf("产品id：%s,产品销量：%v\n", z.Member, z.Score)
	}
	return nil
}
